<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>{{ pageTitle }}</span>
        </div>
      </template>

      <el-form label-width="120px">
        <el-form-item label="选择导入文件" required>
          <el-upload
            :limit="1"
            :auto-upload="false"
            accept=".xls,.xlsx,.csv"
            :on-change="onFileChange"
            :file-list="fileList"
          >
            <el-button type="primary" icon="Upload">选择附件</el-button>
            <template #tip>
              <div class="el-upload__tip text-center">
                <span>支持格式：.xls、.xlsx、.csv，单个文件不超过20MB</span>
                <el-link type="primary" class="link-type" @click="downloadTemplate">下载模板</el-link>
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit" :loading="submitting">保 存</el-button>
          <el-button @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>

      <div>
        <div class="import-log-title">导入记录：</div>
        <el-empty v-if="logs.length === 0" description="暂无记录" />
        <el-timeline v-else>
          <el-timeline-item v-for="(log, idx) in logs" :key="idx" :timestamp="log.time" placement="top">
            <div>
              导入 {{ log.count }} 条数据，成功 {{ log.success }} 条，失败 {{ log.fail }} 条
              <el-link type="primary" style="margin-left: 8px">查看详情</el-link>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup>
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()
import {listMange} from '@/api/comsys/mange.js'
import request from '@/utils/request'

const fileList = ref([])
const submitting = ref(false)
const logs = ref([])

// 根据当前模块生成标题
const module = computed(() => route.path.split('/')[2] || route.query.module)
const titleMap = {
  house: '房屋批量导入',
  building: '楼宇批量导入',
  shop: '商铺批量导入',
  space: '车位批量导入',
  room: '储藏室批量导入',
  mange: '社区管理批量导入'
}
const pageTitle = computed(() => titleMap[module.value] || '批量导入')

onMounted(() => {
  // 同步标签页标题（若支持）
  if (route.meta) route.meta.title = pageTitle.value
})

function onFileChange(file, files) {
  fileList.value = files
}

function reset() {
  fileList.value = []
}

function submit() {
  debugger
  if (fileList.value.length === 0) {
    proxy.$modal?.msgError('请选择上传文件')
    return
  }
  submitting.value = true
  const formData = new FormData()
  formData.append('file', fileList.value[0].raw)
  const url = `/comsys/${module.value}/import`
  request({ url, method: 'post', data: formData, headers: { 'Content-Type': 'multipart/form-data' } })
    .then(res => {
      submitting.value = false
      proxy.$modal?.msgSuccess(res?.msg || '导入成功，正在返回...')
      logs.value.unshift({ time: new Date().toLocaleString(), count: res?.data?.total || 0, success: res?.data?.success || 0, fail: res?.data?.fail || 0 })
      setTimeout(() => {
        listMange()
        router.back()
      }, 500)

    })
    .catch(err => {
      submitting.value = false
      console.error(err)
      proxy.$modal?.msgError('导入失败')
    })
}

function downloadTemplate() {
  const urlMap = {
    building: 'comsys/building/importTemplate',
    house: 'comsys/house/importTemplate',
    room: 'comsys/room/importTemplate',
    shop: 'comsys/shop/importTemplate',
    space: 'comsys/space/importTemplate',
    mange: 'comsys/mange/importTemplate'
  }
  const url = urlMap[module.value]
  if (url) {
    proxy.download(url, {}, `${module.value || 'import'}_template.xlsx`)
  } else {
    proxy.$modal?.msgInfo('该模块模板暂未配置')
  }
}
</script>

<style scoped>
.card-header { font-size: 16px; font-weight: 600; }
.import-log-title { margin: 12px 0; font-weight: 500; }
.app-container { padding-bottom: 24px; }
</style>